import React, { Component } from 'react';
import { Layout } from 'antd';
import Header from './components/layout/Header/Header';
import Aside from './components/layout/Aside/Aside';
import Loading from './components/Loading';
import { IconFont } from './components/IconFont';
import Msg from './components/Msg';
import { connect } from 'react-redux';
import routerConfig from './router';
import './app.less';
import './tantuer.less'; // tantuer skin

@connect(mapStateToProps)
class Main extends Component {
  constructor(props) {
    super(props);
    this.pathname = '';
    this.path = '';
    this.highlightPath = ''; // 查找到的高亮path，
    this.timeout = null;
  }
  componentDidMount() {
    this.pathname = this.props.location.pathname;
    // this.queryMenuList(this.pathname);

    // this.pendingCount();
    // 轮询请求 审核待处理接口，一分钟一次
    // this.timeout = setInterval(() => {
    //   this.pendingCount();
    // }, 60 * 1000);

    // window.onbeforeunload = this.beforeClose;
  }

  beforeClose = (e) => {
    if (this.props.needWarning && this.props.needWarning > 0) {
      e = e || window.event;
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = '';
      }
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return '';
    }
  };

  componentWillReceiveProps(nextProps) {
    console.log(nextProps.needWarning);
    if (nextProps.location.pathname !== this.pathname) {
      this.path = '';
      this.highlightPath = '';
      this.highlight(nextProps.menu, nextProps.location.pathname);
      this.pathname = nextProps.location.pathname;
    }
  }

  componentDidWillUnMount() {
    // clearInterval(this.timeout);
    // this.timeout = null;
  }

  pendingCount = () => {
    this.props.dispatch({ type: 'menu/pendingCount', params: {} });
  };

  // 查询 menu list
  queryMenuList = (pathname) => {
    this.props.dispatch({ type: 'menu/queryMenu', params: {} }).then((data) => {
      this.highlight(data, pathname);
    });
  };

  highlight = (data, pathname) => {
    const path = this.regPath(pathname);
    data.forEach((item) => {
      if (path !== pathname) {
        const matchPathIds = this.toMatch(item, pathname);
        if (matchPathIds && matchPathIds instanceof Array) {
          this.highlightPath = path;
          this.props.dispatch({ type: 'menu/updateAsideHighlight', ids: matchPathIds });
        } else {
          this.highlight(data, path);
          this.path = path;
        }
      } else {
        const matchPathIds = this.toMatch(item, path);
        if (matchPathIds && matchPathIds instanceof Array) {
          this.highlightPath = path;
          this.props.dispatch({ type: 'menu/updateAsideHighlight', ids: matchPathIds });
        }
      }
    });
  };

  toMatch = (o, path) => {
    if (o.route === path) {
      return [o];
    }
    if (o.children && o.children.length) {
      for (var idx = 0; idx < o.children.length; idx++) {
        var tm = this.toMatch(o.children[idx], path);
        if (tm) {
          const arr = [o];
          tm.forEach((it) => {
            arr.push(it);
          });
          return arr;
        }
      }
    }
  };

  regPath = (pathname) => {
    const pathRegAdd = /.+(?=\/(add|import|export|setting|download|customParams))/;
    const pathRegEdit = /.+(?=\/[\w_-]+\/(detail|edit|version|copy|list))/;
    const rePath = pathname.match(pathRegEdit) || pathname.match(pathRegAdd);
    const path = rePath === null ? pathname : rePath[0];
    return path;
  };

  renderBreadCrumb = () => {
    const menuCurrent = this.props.asideHighlight.find((item) => item.route === this.highlightPath) || {};
    const route = this.props.location.pathname.replace(/\/[\w_-]+(?=\/(detail|edit|version|copy|list))/g, '/:id');
    const routeCurrent = routerConfig.find((item) => item.path === route);
    const isPrev = menuCurrent.route !== route;
    return (
      <>
        {routeCurrent && (
          <div className='breadcrumb'>
            <span className='breadcrumb-title'>
              {isPrev && (
                <IconFont
                  type='iconreback1'
                  className='breadcrumb-prev'
                  onClick={() => {
                    !this.path ? this.props.history.push(menuCurrent.route) : this.props.history.push(this.path);
                  }}
                />
              )}
              {routeCurrent.name}
            </span>
            <span className='breadcrumb-des'>{routeCurrent.des}</span>
          </div>
        )}
      </>
    );
  };

  render() {
    return (
      <div>
        <Loading />
        <Msg />
        {window.__POWERED_BY_QIANKUN__ ? (
          <div className='content'>{this.props.children}</div>
        ) : (
          <Layout className='layout tantuer tantuer-layout-main'>
            <Layout.Sider width='200' collapsed={this.props.collapsed} collapsedWidth={60}>
              <Aside {...this.props} />
            </Layout.Sider>
            <Layout className={this.props.collapsed ? 'layout-content collapsed' : 'layout-content'}>
              <Layout.Header className='header-fixed'>
                <Header {...this.props} />
              </Layout.Header>
              <Layout.Content>
                {this.renderBreadCrumb()}
                <div className='content'>{this.props.children}</div>
              </Layout.Content>
            </Layout>
          </Layout>
        )}
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    ...state.menu,
    needWarning: state.pageClose.needWarning,
  };
}
export default Main;
